import json
import random
import time

from flask import jsonify, stream_with_context, Response, request

from myapp.entities.Consultation import Consultation
from myapp.utils import GPT
from myapp.utils.RedPrint import RedPrint

api = RedPrint('messages')


# 测试接口
@api.route('/test', methods=['GET'])
def test():
    user_consultation = GPT.question(1, 1, '你好')
    print(user_consultation)
    return Response('ok')


# 流式推送
@api.route('/sendMessages', methods=['POST'])
def sendMessages():
    userid = request.form.get('userid')
    consultationid = request.form.get('consultationid')
    messages = request.form.get('messages')
    gpt_response = GPT.question(userid, consultationid, messages)
    results = []

    def generate():
        for line in gpt_response.iter_lines():
            data = GPT.handleLine_todict(line)
            if data is not None:
                if data['is_end'] is True:
                    full_answer = ''.join(results)
                    consultation = Consultation.query.filter_by(userid=userid, consultationid=consultationid).first()
                    consultation.add_answer(full_answer)

                results.append(data['result'])
                json_data = json.dumps(data)
                yield f"data: {json_data}\n\n"
                time.sleep(1)

    return Response(stream_with_context(generate()),
                    mimetype='text/event-stream')
